package com.cgbl.service.ui

import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavCallback
import com.cgbl.service.BR
import com.cgbl.service.R
import com.cgbl.service.adapter.TagManagerAdapter
import com.cgbl.service.databinding.AppActivityTagManagerBinding
import com.cgbl.service.vm.TagManagerViewModel
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.MemberAdapterBean
import com.robot.base.model.TagListBean
import com.robot.base.model.TeamListBean
import com.robot.base.util.LiveDataEventManager
import com.robot.base.util.arouter.ARouterUtil
import java.util.regex.Pattern

@Route(path = AppConstants.Router.Project.A_TAG_MANAGER)
class TagManagerActivity : GLBaseActivity<AppActivityTagManagerBinding, TagManagerViewModel>() {

    lateinit var tagManagerAdapter: TagManagerAdapter

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_tag_manager

    override fun initVariableId(): Int = BR.viewModel

    override fun initComponents() {
        initTiterBar()
        tagManagerAdapter = TagManagerAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = tagManagerAdapter
        }
        tagManagerAdapter.setOnItemClickListener { adapter, view, position ->
            val id = tagManagerAdapter.data[position].id
            ARouterUtil.goToActivityWithBundle(
                AppConstants.Router.Project.A_EDIT_TAG,
                Bundle().apply {
                    putString(AppConstants.BundleKey.ID, id)
                })
        }
        binding.etSearch.addTextChangedListener(onTextChanged = { text, _, _, _ ->
            val char = text.toString()
            val result = viewModel.fetchLabelByKeyword(char)
            tagManagerAdapter.setNewInstance(result)
            if (TextUtils.isEmpty(char)) {
                tagManagerAdapter.setNewInstance(viewModel.cacheList)
            }
        })
        viewModel.fetchLabelList()
    }

    private fun initTiterBar() {
        val titleView = findViewById<TextView>(R.id.tv_title)
        val backView = findViewById<ImageView>(R.id.iv_back)
        titleView?.text = "标签"
        backView?.setOnClickListener { finish() }
    }

    override fun initViewObservable() {
        viewModel.uc.tagListDataEvent.observe(this) {
            tagManagerAdapter.setNewInstance(it as MutableList<TagListBean>?)
        }
        LiveDataEventManager.observerRefreshLabelEvent(this) {
            viewModel.fetchLabelList()
        }
    }

}